import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import http from '../../http/index'

const initialState: { value: any } = {
  value: {
    users: [],
    type: 0, // 0  好友资料页面  1 添加好友页面
    current: 0, // 当前选中的
  },
};


try {
  const type_str = localStorage.getItem("friend_type")
  const current_str = localStorage.getItem("friend_current")
  const list_str =  localStorage.getItem("friend_list")
  if (list_str) {
    initialState.value.list = JSON.parse(list_str);
    initialState.value.current = current_str ? parseInt(current_str) : 0
    initialState.value.type = type_str ? parseInt(type_str) : 0
  }
} catch (error) {
  console.error('Error initializing conversation state:', error);
}



export const refreshFriendList: any = createAsyncThunk('/friend/refresh', async () => {
  const response = await http.get("/friendList");
  const users = response.data;
  return { users};
})


export const forceRefreshFriendList: any = createAsyncThunk('/friend/forcelist', async () => {
    const response = await http.get("/friendList");
    const users = response.data;
    return { users, type: 0, current: 0 };
})






export const friendSlice = createSlice({
  name: "friend",
  initialState,
  reducers: {
    setType: (state, action) => {
      state.value.type = action.payload;
      localStorage.setItem('friend_type', `${action.payload}`)
    },
    setCurrent: (state, action) => {
      state.value.current = action.payload;
      localStorage.setItem('friend_current', `${action.payload}`)
    }
  },
  extraReducers: (builder) => {
    builder.addCase(forceRefreshFriendList.fulfilled, (state, action) => {  
      const payload: any = action.payload;
      localStorage.setItem("friend_type", `0`)
      localStorage.setItem("friend_current", `0`)
      localStorage.setItem("friend_list", JSON.stringify((payload.users ?? [])) )
      state.value = payload;
    }).addCase(refreshFriendList.fulfilled, (state, action) => {  
      const payload: any = action.payload;
      state.value.users = payload.users;
      localStorage.setItem("friend_list", JSON.stringify((payload.users ?? [])))
    });
  },
})

export const { setType, setCurrent } = friendSlice.actions;

export default friendSlice.reducer